module client.ImClient;

import hunt.logging;
import std.stdio;
import msgtrans;
import message.MsgDefine;
import message.Constants;

/**
 * IM 连接用户（长连接对象）
 */
class ImClient {

    private __gshared ImClient _instance;

    private TransportSession[ulong] _forwardClientMap;

    private uint _size;

    static public ImClient getInstance()
    {
        if (_instance is null)
        {
            _instance = new ImClient();
        }
        return _instance;
    }

    public void addForwardClient(TransportSession client,ulong id , uint src)
    {
        ulong mixId = idMixSrc(id, src);
        synchronized(this)
        {
            if (mixId in _forwardClientMap)
            {
                logErrorf("ImClient id(%s) by (%s) have exist!", id , src);
            }

            _forwardClientMap[mixId] = client;
            _size += 1;
        }
    }

    public ulong idMixSrc (ulong id, uint src)
    {
         ulong mixId = ((id << 16) | cast(ushort)src);
         return mixId;
    }

    public void deleClient(ulong id)
    {
         synchronized(this)
         {
             if (id    in _forwardClientMap)
             {
                 _forwardClientMap.remove(id);
             }
             else
             {
                 logErrorf("ImClient id(%s) is not exist!", id);
             }
         }
    }

    public TransportSession[] getImClient(ulong id)
    {
            TransportSession[ulong] tmp;
            TransportSession[] array;
            synchronized(this)
            {
                tmp = _forwardClientMap;
                //return _forwardClientMap.get(id,null);
            } // session.setAttribute(SESSIONKEY.USER,res.user);

            foreach (k , v ; tmp)
            {
                    if (id == (k >> 16))
                    {
                            array ~= v;
                    }
                    //AuthenticateREQ authorize = cast(AuthenticateREQ)(session.getAttribute(SESSIONKEY.SRC));
            }
            
            return array;
    }

    public TransportSession getImClientByMixId(ulong id)
    {
        synchronized(this)
        {
            return _forwardClientMap.get(id,null);
        }
    }



}

